<template>
  <div>
    <attributeCateSelect
      :select_disabled="CARD_SCENE == 1"
    ></attributeCateSelect>

    <div class="attr_list_card">
      <div class="attr_list" v-show="CARD_SCENE == 0">
        <el-card>
          <el-button
            type="primary"
            size="default"
            icon="Plus"
            @click="CHANGE_CARD(1)"
            :disabled="!AttributeCateStore.key_third"
          >
            添加平台属性
          </el-button>

          <div class="table_section">
            <el-table :data="tableData" stripe border>
              <el-table-column
                label="序号"
                width="100"
                type="index"
                align="center"
              />
              <el-table-column prop="catename" label="属性名称" width="200" />
              <el-table-column
                prop="attrValueList"
                label="属性值名称"
                min-width="400"
              >
                <template #default="{ row }">
                  <el-tag
                    v-for="tag in row.attrValueList"
                    :key="tag.attr_id"
                    class="tag"
                  >
                    {{ tag.valueName }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="150">
                <template #default="scope">
                  <el-button
                    type="primary"
                    icon="Edit"
                    size="small"
                    @click="CHANGE_CARD(1, scope.row.id)"
                  ></el-button>
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    @click="DELETE_ATTR(scope.row.id)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination_section">
            <el-pagination
              v-model:current-page="form.pageNo"
              v-model:page-size="form.limit"
              :page-sizes="[10, 20, 50, 100]"
              background
              layout="prev, pager, next,jumper, ->,sizes,total "
              :total="total"
              @size-change="GET_LIST"
              @current-change="GET_LIST"
            />
          </div>
        </el-card>
      </div>
      <div class="add_edit_attr" v-show="CARD_SCENE == 1">
        <el-card>
          <div class="attr_name">
            <el-form class="login_form" ref="ruleFormRef">
              <el-form-item label="属性名称">
                <el-input
                  v-model="attrParams.catename"
                  style="width: 240px"
                  placeholder="请您输入属性名称"
                />
              </el-form-item>
            </el-form>
          </div>
          <div class="attr_btns">
            <el-button
              type="primary"
              size="default"
              icon="Plus"
              @click="ADD_ATTRVALUE_ROW()"
              :disabled="!attrParams.catename"
            >
              添加属性值
            </el-button>
          </div>

          <div class="table_section">
            <el-table
              :data="attrParams.attrValueList"
              stripe
              border
              max-height="500"
            >
              <el-table-column
                label="序号"
                width="100"
                type="index"
                align="center"
              />

              <el-table-column prop="valueName" label="属性值">
                <template #default="{ row, $index }">
                  <el-input
                    :ref="(el) => ROW_REF_CALLBACK(el, $index)"
                    v-model="row.valueName"
                    placeholder="请您输入属性值"
                    clearable
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    @click="DELETE_ATTRVALUE_ROW($index)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="save_btns">
            <el-button
              type="primary"
              size="default"
              @click="ADDUPDATE_ATTR()"
              :disabled="
                !AttributeCateStore.key_third ||
                attrParams.attrValueList.length == 0 ||
                !attrParams.catename
              "
            >
              保存
            </el-button>

            <el-button size="default" @click="CHANGE_CARD(0)">取消</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'attribute',
}
</script>
<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'

import { onMounted, onBeforeUnmount, ref, reactive, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import {
  resHasAttribute,
  reqAddOrUpdateAttribute,
  reqDeletAttribute,
} from '@/api/product'
import type {
  Attr,
  AttributeListResponseData,
  AttrList,
} from '@/api/product/type'
import { publicConfirm } from '@/utils/handleData'

import useAttributeCate from '@/store/modules/attributeCateStore'
let AttributeCateStore = useAttributeCate()
const { key_third } = storeToRefs(AttributeCateStore)

onMounted(() => {})

onBeforeUnmount(() => {
  AttributeCateStore.$reset()
})
const ruleFormRef = ref<FormInstance>()
let total = ref<number>(1)
let form = reactive({
  pageNo: 1,
  limit: 10,
})
let tableData = ref<AttrList>([])

const attrParams_init = {
  id: 0,
  catename: '',
  categoryId: AttributeCateStore.key_third,
  categoryLevel: 3,
  attrValueList: [],
}
let attrParams = reactive<Attr>({ ...attrParams_init })

const GET_LIST = async (category2Id: unknown = 0) => {
  Object.assign(form, { category2Id })
  let result: AttributeListResponseData = await resHasAttribute(form)
  if (result.code == 200) {
    tableData.value = result.data
    console.log('更新后的数据:', tableData)
  }
}

// 展示属性列表0 添加修改属性 1
let CARD_SCENE = ref<number>(0)
const CHANGE_CARD = (scene, id = 0) => {
  INIT_ATTR_ROW({ scene, id })
  CARD_SCENE.value = scene
}

let ROW_REF_ARRAY = ref<any>([])
const ROW_REF_CALLBACK = (cv, index) => {
  ROW_REF_ARRAY.value[index] = cv
}

const ADD_ATTRVALUE_ROW = () => {
  attrParams.attrValueList.push({
    valueName: '',
  })
  nextTick(() => {
    if (ROW_REF_ARRAY.value.length > 0) {
      const lastInput = ROW_REF_ARRAY.value[ROW_REF_ARRAY.value.length - 1]
      console.log(lastInput)
      lastInput.focus()
    }
  })
}
const DELETE_ATTRVALUE_ROW = (index) => {
  attrParams.attrValueList.splice(index, 1)
}

const INIT_ATTR_ROW = ({ scene, id }) => {
  ROW_REF_ARRAY.value = []
  attrParams.categoryId = key_third.value || 0
  if (scene == 0) {
    // 切回列表
    Object.assign(attrParams, { ...attrParams_init, attrValueList: [] })
  } else if (scene == 1) {
    //添加或者修改属性
    if (id > 0) {
      // 修改属性
      const found = tableData.value.find((item) => item.id === id)
      if (found) {
        Object.assign(attrParams, found)
      }
      console.log(attrParams)
    } else {
      //新增
    }
  }
}

const ADDUPDATE_ATTR = async () => {
  //   if (!ruleFormRef.value) return
  //   await ruleFormRef.value.validate()
  let result: any = await reqAddOrUpdateAttribute(attrParams)
  let type = '添加'
  if (attrParams.id) {
    type = '修改'
  }
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
  } else {
    ElMessage({
      type: 'error',
      message: `${type}成功`,
    })
  }
  CHANGE_ATTR_CALLBACK()
}
// 删除对话框
const DELETE_ATTR = async (id = 0) => {
  const flag = await publicConfirm({
    title: '提示',
    content: '确认删除该属性？',
  })
  let type = '删除'
  if (flag) {
    let result: any = await reqDeletAttribute(id)
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: `${type}成功`,
      })
      GET_LIST()
    } else {
      ElMessage({
        type: 'error',
        message: `${type}失败`,
      })
    }
  } else {
    ElMessage({
      type: 'info',
      message: `取消${type}`,
    })
  }
}
const CHANGE_ATTR_CALLBACK = () => {
  CHANGE_CARD(0)
  GET_LIST()
}
watch(key_third, (newValue) => {
  //   console.log('sum变化了', newValue, oldValue)
  if (newValue) {
    GET_LIST(newValue)
  } else {
    tableData.value = []
  }
})
</script>

<style scoped lang="scss">
.table_section {
  margin: 10px 0;
  .tag {
    margin: 5px;
  }
}
.attr_list_card {
  margin-top: 10px;
}
</style>
